#include "backup_thread.h"

BackupThread::BackupThread(QMobex *mobex, QFile *file, QByteArray phoneMemory, QObject *parent):
    QThread(parent)
{
    this->mobex = mobex;
    this->file = file;
    memory = phoneMemory;
    aborted = false;
}

BackupThread::~BackupThread() {
    mobex = 0;
    qDebug("Backup thread destrucktor");
}

void BackupThread::abort() {
    aborted = true;
    this->quit();
}

void BackupThread::run() {
    int i = 0;//part counter
    int k = 0;//saved Contacts
    QHash<int,QByteArray> responsData;
    while (!aborted) {
        responsData.clear();
        QByteArray response = mobex->contactsLoad(responsData, i, memory);

        QHashIterator<int, QByteArray> iter(responsData);
        while(iter.hasNext()) {
            iter.next();
            QByteArray toWrite = iter.value();
            toWrite.append("\r\n");

            file->write(toWrite);

            ++k;
         emit(saved(k));
     }
        file->flush();
        if(response == QMobex::PARAMS_NEXT) {
             ++i;//increme
        }
        else {
            abort();
        }

    }
    this->quit();
}
